import os,re,json

from fabric import Connection
"""
author:jack

"""
def getNmap(conn,area,lanNum):
    """  通过执行 namp 扫描某网段"""
    cmdTpl = "nmap  -sP -PR 192.168.{lanNum}.* -oN carea{lanNum}.txt"
    nmap = conn.run(cmdTpl.format(lanNum=lanNum))
    nmpreg = re.findall('Nmap scan report for ([\d\.?]+)\nHost is up .*\nMAC Address: ((?:[0-9a-fA-F]:?){12}) ',nmap.stdout)
    for r in nmpreg :
        area[r[0]] = [r[1]]
 
        
def getIpnei(conn,area):
    """  ip 得到 mac的映射"""
    
    ipnei = conn.run( "ip nei" )
    ipreg = re.findall(r'([\d\.?]{7,15}) dev .*? ((?:[0-9a-fA-F]:?){12})',ipnei.stdout)
    for r in ipreg :
        area[r[0]] = [r[1]]
     
            
def doOne(conn,lanNum):
    """ 之一个段 """
    
    area = {} #kv简单去重
    getNmap(conn,area,lanNum)
    getIpnei(conn,area)
    # ---- 数据去重
    dpData = {}
    for k   in area   :
        spk = k.split('.')
        if spk[2]==str(lanNum):
            #print(spk,k,area[k][0])
            dpData[k] = area[k][0]
    # ---- 写入文件
    dpFile = r'D:\jack\云文档\src\json\网段{}IP分布.json'.format(lanNum)
    with open(dpFile, 'w') as f:
        json.dump(dpData, f,indent=3,ensure_ascii=False,sort_keys=True) 
if __name__ == "__main__":
    conn = Connection("root@192.168.0.1", connect_kwargs={"password": "wsf119900"})
    for n in [6,34,20,88,17,15,87]:
        doOne(conn,n)
    
    
